from threading import Thread
from pytask.task import *
from time import sleep, time

class MyTask(DelayedTask):
    def run(self):
        print 'Execute the task...'
        sleep(3)

class Test(Thread):
    def __init__(self, dq, name='Test'):
        Thread.__init__(self)
        self.dq = dq;
        self.setName(name)

    def run(self):
        while True:
            task = self.dq.take()
            if task.isExit():
                print 'Thread is going to shutdown now.'
                # put the logo back to queue so other theads can exit
                pq.put(task)
                break
            task.preRun(self.dq)
            print self.getName() + ' ' + str(task)
            task.run()
            task.postRun(self.dq)

class Add(Thread):
    def __init__(self, dq, name='Test'):
        Thread.__init__(self)
        self.dq = dq;
        self.setName(name)

    def run(self):
        for index in range(size):
            import random
            r = random.randint(5, size)
            sleep(1)
            task = MyTask(time() + r, r, 'Task' + str(index))
            print task
            pq.put(task)
        sleep(100)
        # after 100s exit
        pq.put(ExitTask)

if __name__ == '__main__':
    d = []
    size = 200
    pq = DQueue()

    take = Test(pq, 't1-')
    take.start()
    take = Test(pq, 't2-')
    take.start()
    take = Test(pq, 't3-')
    take.start()
    take = Test(pq, 't4-')
    take.start()
    take = Test(pq, 't5-')
    take.start()

    add = Add(pq, 'A--')
    add.start()